home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_13_04 / allison / swap2.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-02-06  |  731 b   |  41 lines

  1. LISTING 9 - A function template for swap()
  2.  
  3. //swap2.c 
  4. #include <iostream.h>
  5. #include "complex.h"
  6.  
  7. template<class T>
  8. void swap(T &x, T &y)
  9. {
  10.     T temp = x;
  11.     x = y;
  12.     y = temp;
  13. }
  14.  
  15. main()
  16. {
  17.     int i = 1, j = 2;
  18.     swap(i,j);
  19.     cout << "i == " << i << ", j == " << j << endl;
  20.  
  21.     double x = 3.0, y = 4.0;
  22.     swap(x,y);
  23.     cout << "x == " << x << ", y == " << y << endl;
  24.  
  25.     char *s = "hi", *t = "there";
  26.     swap(s,t);
  27.     cout << "s == " << s << ", t == " << t << endl;
  28.  
  29.     complex c1(5,6), c2(7,8);
  30.     swap(c1,c2);
  31.     cout << "c1 == " << c1 << ", c2 == " << c2 << endl;
  32.     return 0;
  33. }
  34.  
  35. // Output:
  36. i == 2, j == 1
  37. x == 4, y == 3
  38. s == there, t == hi
  39. c1 == (7,8), c2 == (5,6)
  40.  
  41.